package com.right.netty.pipeline;

import com.right.handler.PackageHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;

/**********************************************
 * @author pillar
 * @date 2018/3/22
 **********************************************/
@ChannelHandler.Sharable
@Slf4j
public class CompositeMessageHandler extends ChannelInboundHandlerAdapter{

    private final List<PackageHandler> messageListeners = new CopyOnWriteArrayList<>();
    public void addLast(PackageHandler... packageHandler) {
        Objects.requireNonNull(packageHandler, "packageHandler is required");
        messageListeners.addAll(Arrays.asList(packageHandler));
    }

    public CompositeMessageHandler() {
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            if (msg != null) {
                doHandleMessage(ctx, msg);
            }
        }finally {
            ReferenceCountUtil.release(msg);
        }
    }

    private void doHandleMessage(ChannelHandlerContext ctx, Object msg) {
        List<String> dataList = new ArrayList<>();
        try {
            String data = (String) msg;
            data = data.substring(2).trim();
            String[] ss = data.split(",");
            for (String s : ss) {
                if (s.length() > 0) {
                    dataList.add(s);
                }
            }
            if (((String)msg).startsWith("**,301")){
                dataList.add(data.substring(1,6));
            }else if (((String)msg).startsWith("**,205")){
                dataList.add(data.substring(1,6));
            }else if (((String)msg).startsWith("**,201")){
                dataList.add(data.substring(1,6));
            }else if (((String)msg).startsWith("**,202")){
                dataList.add(data.substring(1,6));
            }else if (((String)msg).startsWith("**,206")){
                dataList.add(data.substring(1,6));
            }
        } catch (Exception e) {
            return;
        }

        boolean doNext;
        for (int i = 0, size = messageListeners.size(); i < size; i++) {
            PackageHandler handler = messageListeners.get(i);
            try {
                if (handler.applies(dataList)) {
                    doNext = handler.handleMessage(ctx, dataList);
                    if (!doNext) {
                        break;
                    }else {
                        i = 0;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
              log.error("指令处理异常={}",e.toString());
            }
        }
    }
}
